package util;

import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

/**
 *
 * @author Silvanei S
 */
public class MonetarioField extends PlainDocument{
    
    public static final int NUMERO_DIGITOS_MAXIMO = 19; 

    @Override
    public void insertString(int offs, String str, AttributeSet a) throws BadLocationException { 

        String texto = getText(0, getLength()); 

        for (int i = 0; i < str.length(); i++) { 
            char c = str.charAt(i); 
            if (!Character.isDigit(c) && c != '.' && c != ',') { 
                return; 
            } 
        } 

        if(texto.length() < MonetarioField.NUMERO_DIGITOS_MAXIMO){ 
            super.remove(0, getLength()); 
            texto = texto.replace(".", "").replace(",", ""); 
            str = str.replace(".", "").replace(",", ""); 
            StringBuilder s = new StringBuilder(texto + str); 
               
            if (s.length() > 0 && s.charAt(0) == '0') { 
               s.deleteCharAt(0); 
            } 

            if(s.length() < 3) { 
                if (s.length() < 1) { 
                    s.insert(0,"000"); 
                } else if (s.length() < 2) { 
                    s.insert(0,"00"); 
                } else { 
                    s.insert(0,"0"); 
                } 
            } 

            s.insert(s.length()-2, ","); 

            if(s.length() > 6) { 
                s.insert(s.length()-6, "."); 
            } 

            if(s.length() > 10) { 
                s.insert(s.length()-10, "."); 
            }
            
            if(s.length() > 14) { 
                s.insert(s.length()-14, "."); 
            }
            
            if(s.length() > 18) { 
                s.insert(s.length()-18, "."); 
            }
            
            super.insertString(0, s.toString(), a); 
        } 
    } 
 

} 
